package com.example.demoback.web;

import com.example.demoback.entity.LoginInfo;
import com.example.demoback.entity.Result;
import com.example.demoback.entity.User;
import com.example.demoback.mapper.UserMapper;
import com.example.demoback.service.ServiceException;
import com.example.demoback.service.UserService;
import com.example.demoback.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("user")
public class UserAction {

    @Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    @RequestMapping("queryAll")
    List<Map<String,Object>> queryAll(){
        return userMapper.selectAll();
    }

    @RequestMapping("login")
    Result login(String username, String password){
        try{
            LoginInfo loginInfo=userService.login(username,password);
            return new Result(1,"登录成功！",loginInfo);
        }catch (ServiceException e){
            return new Result(0,e.getMessage(),null);
        }
    }

    @RequestMapping("getLoginedUser")
    Result getLoginedUser(@RequestHeader(value = "token", required = false) String token){
        Integer id = null;
        if(token!=null){
            Claims claims = JwtUtils.parseJWT(token);
            id = claims.get("id", Integer.class);
        }


        // 3. 获取用户信息（假设Payload中包含userId和role）
        log.info("从token获取id："+id);
        if(id==null){
            return new Result(0,"未登录",null);
        }
       User user=userService.getById(id);
        return new Result(1,"已登录",user);
    }


    @RequestMapping("Logout")
    Result logout(){
        log.info("用户退出");
        return new Result(1,"退出成功",null);
    }

    @RequestMapping("register")
    Result register(User user){
        try {
            userService.register(user);
            return new Result(1,"注册成功",user);
        } catch (ServiceException e) {
            return new Result(0,e.getMessage(),user);
        }
    }

    @RequestMapping("save")
    Result save(User user) {
        login(user.getUsername(),user.getPassword());
        try {
            // 1. 保存用户信息到数据库
            userService.save(user);

            // 4. 返回最新数据给前端
            return new Result(1, "保存成功",user);
        } catch (ServiceException e) {
            // 保留原始用户数据用于调试
            return new Result(0, e.getMessage(), user);
        }
    }

    @RequestMapping("selectbyid")
    public User getUserById(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在"); // 或自定义异常
        }
        return user;
    }
}
